package com.david.easyExcel.BosDemo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;

/**
 * 方正宇写的tcp接出
 * 源代码：
 * out[i]=48;可以转换为out[i]=ox30
 * 将所有的8转换为DATALENGTH
 *
 *
 */
public class TcpSenderUtil {

    private static final int DATALENGTH=8;
    private static final Charset charset;
    private static final int TIMEOUT=60000;

    private TcpSenderUtil(){

    }

    /**
     * @param ip
     * @param port
     * @param sendXml
     * @return 返回将sendXml发出后接收到的报文
     */
    public static String send(String ip,int port,String sendXml){

        try {
            Socket s=new Socket();
            Throwable var4=null;
            String var12;
            try {
                s.connect(new InetSocketAddress(ip,port),60000);
                OutputStream os=s.getOutputStream();
                byte[] b=pack(sendXml);
                os.write(b);
                os.flush();
                InputStream is=s.getInputStream();
                byte[] lenb=new byte[8];
                IOUtils.readFully(is,lenb);
                String dataLen=new String(lenb,charset);
                int len=Integer.parseInt(dataLen);//数据长度
                byte[] inData=new byte[len];
                IOUtils.readFully(is,inData);
                var12=new String(inData,charset);
            }catch (Throwable var22){
                var4=var22;
                throw var22;
            }finally {
                if (s!=null){
                    if (var4!=null){
                        try {
                            s.close();
                        }catch (Throwable var21){
                            var4.addSuppressed(var21);
                        }
                    }else {
                        s.close();
                    }
                }
            }
            return var12;
        }catch (IOException var24){
            throw new RuntimeException(var24);
        }
    }

    /**
     * 数组前8位记录的是字节数组的长度，8位后面记录的是具体数据
     * @param xml 需要传输的xml报文
     * @return
     */
    private static byte[] pack(String xml){
        byte[] xmlBytes=xml.getBytes(charset);//使用UTF-8格式将字符串转换为字节数组
        int len = xmlBytes.length;
        byte[] out = new byte[8 + len];
        byte[] templen = String.valueOf(len).getBytes(charset);//
        if (templen.length>8){
            throw new RuntimeException("too big xml");
        }else {
            for (int i=0;i<8-templen.length;++i){
                out[i]=48;
            }
        }
        System.arraycopy(templen,0,out,8-templen.length,templen.length);
        System.arraycopy(xmlBytes,0,out,8,len);
        return out;
    }
    static {//静态块在类加载时会执行
        charset= StandardCharsets.UTF_8;
    }
}
